#!/usr/bin/env python
# $Id: test2-22.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"

import datetime
import optparse
import sys
import random
import socket
import sqlalchemy
import re

from Cheetah.Template import Template

from venya.lib.exception import GetOptError
from venya.lib import cmdparser
from venya.lib import ip
from venya.lib import sql
from venya.lib import log

class dnssql(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-t", "--template", default = "dns.tmpl",
            help = "Template File to use for DNS", type = "str", dest = "tmpl"),
         ) + cmdparser.GetOpt.option_list

   def __init__(self, **Keywords):
      super(self.__class__, self).__init__(**Keywords)
      self._netdot = None

   def handle(self):
      (options, args) = self.parse()

      self._netdot = sql.mysql("netdot",
            "sirius", "djanet", "oS9XckUcTAHc5rjlcPt1")
      device = self._netdot.device
      ipblock = self._netdot.ipblock
      interface = self._netdot.interface
      rr = self._netdot.rr
      zone = self._netdot.zone
      site = self._netdot.site
      phy = self._netdot.physaddr
      fh = None

      if options.tmpl:
         time = datetime.date.today()
         serial = time.strftime("%Y%m%d") + str(random.randint(1, 99))
         config = {}
         config["dnsName"] = "neteng.kashyapa.net"
         config["serverName"] = socket.gethostname()
         config["serial"] = serial

         template = Template(file = options.tmpl, searchList = [config])
         configfile = "%s.zone" %config["dnsName"]
         try:
            try:
               fh = open(configfile, "w")
            except OSError as err:
               self.error(err.message)
            else:
               fh.write(str(template))
         except Cheetah.NameMapper.NotFound as err:
            self.error(err.message)

      """
      (281L, 1454L, 17406L, 'FOC1310V0R3', 23L, 'YnAYOpM0TX9pj8P4yO', 0)
      """
      for ix in device.q.values(device.id, device.name, device.snmp_target,
            device.serialnumber, device.site, device.community, device.product):
         deviceName = None
         record = None
         [sitename for sitename in site.q.filter(
            site.id == ix[4]).values(site.name)]
         [(zid, devname) for (zid, devname) in rr.q.filter(
            rr.id == ix[1]).values(rr.zone, rr.name)]
         [zname for zname in zone.q.filter(zone.id == zid).values(zone.name)]
         if zname[0] == "neteng.ssnsgs.net":
            deviceName = devname

         if deviceName:
            record = "%s | %s | %s | %s" %(deviceName, sitename[0],
                  ix[3], ix[5])

         if ix[2] != 0:
            [(ipaddr, prefix, version) for (ipaddr,
               prefix, version) in ipblock.q.filter(ipblock.id == ix[2]).values(
                  ipblock.address, ipblock.prefix, ipblock.version)]

            try:
               address = ip.ip(int(ipaddr), prefix = prefix, version = version)
            except ip.IPError as err:
               print(err.message)
            else:
               if fh and deviceName:
                  fh.write("%s\t\tIN\tA\t\t%s\n" %(deviceName, str(address)))

         if fh and record:
            fh.write("%s\t\tIN\tTXT\t\"%s\"\n" %(deviceName, record))

         if deviceName:
            for jy in interface.q.filter(interface.device == ix[0]).values(
                  interface.id, interface.name, interface.speed,
                  interface.type, interface.physaddr):
               address = None
               ifid = int(jy[0])
               try:
                  [(addr, prefix, version) for (addr,
                     prefix, version) in ipblock.q.filter(
                        ipblock.interface == ifid).values(ipblock.address,
                           ipblock.prefix, ipblock.version)]
               except sqlalchemy.exc.InvalidRequestError as err:
                  pass

               name = None
               if jy[1].find("Adaptive") == 0:
                  reif = re.compile("Adaptive Security Appliance '(.*)'.*")
                  match = reif.search(jy[1])
                  if match:
                     name = match.groups()[0]
               elif jy[1].find("Firewall Services Module") == 0:
                  fwif = re.compile("Firewall Services Module '(.*)'.*")
                  match = fwif.search(jy[1])
                  if match:
                     name = match.groups()[0]
               else:
                  name = jy[1]

               iftype = None
               if jy[3] == "propVirtual":
                  iftype = "virtual"
               elif jy[3] == "l2vlan":
                  iftype = "vlan"
               elif jy[3] == "softwareLoopback":
                  iftype = "loopback"
               elif jy[3] == "ethernetCsmacd":
                  iftype = "ethernet"
               elif jy[3] == "tunnel":
                  iftype = jy[3]
               elif jy[3] == "other":
                  iftype = "unknown"

               ifName = name
               phyAddr = None
               if jy[4]:
                  [address for address in phy.q.filter(
                     phy.id == int(jy[4])).values(phy.address)]
                  if address:
                     phyAddr = address[0].lower()
                     address = None

               if addr and prefix and version:
                  name = name.lower().replace("/","-")
                  address = ip.ip(int(addr), prefix = prefix, version = version)
                  if len(address) == 32:
                     fh.write("%s.%s\t\tIN\tA\t\t%s\n" %(
                        name, deviceName, address))
                  else:
                     if version == 4:
                        fh.write("%s.%s\t\tIN\tAPL\t\t1:%s\n" %(
                           name, deviceName, address))
                     elif version == 6:
                        fh.write("%s.%s\t\tIN\tAPL\t\t2:%s\n" %(
                           name, deviceName, address))

                  addr = prefix = version = None

                  if iftype:
                     record = "%s | %s | %s | %d | %s" %(deviceName,
                           ifName, iftype, jy[2], phyAddr)
                     fh.write("%s.%s\t\tIN\tTXT\t\"%s\"\n" %(name,
                        deviceName, record))

      """
      for ix in ipblock.q.filter(ipblock.parent == 0).values(
            ipblock.address, ipblock.prefix, ipblock.version):
         if ix[0] != 0:
            address = None
            try:
               if ix[2] == 4:
                  if ix[1] != 32:
                     address = ip.ip(
                           int(ix[0]), prefix = ix[1], version = ix[2])
               else:
                  address = ip.ip(int(ix[0]), prefix = ix[1], version = ix[2])
            except ip.IPError as err:
               print(err.message)
               continue
            else:
               if address:
                  print(address)
      """

      if fh:
         fh.close()

if __name__ == "__main__":
   dnshandle = None
   try:
      dnshandle = dnssql(version = 1.0, args = sys.argv)
      if len(dnshandle) <= 1:
         dnshandle.printhelp()
      else:
         dnshandle.handle()
   except GetOptError, message:
      print(message)
      sys.exit(1)
